var app = getApp();
var ajax = require('../../utils/ajax.js');
var util = require('../../utils/util.js');
var common = require('../../utils/common.js');
var search = require('../../components/cInfoSearch/cInfoSearch.js');
var MPage = require('../MPage.js');

Page(common.extendPage(MPage, {
    data: {
        dataLoaded: false,
        isCatHide: true,

        curTy: '',
        catList: [],
        noteList: [],

        page: 1,
        loading: false,
        moreLoading: false,
        noMore: false,
        group: 1,
        isLogin: '',
        currentTab: 0,
        from: '',
        q: '',
        serchTip: '点击搜索开始',
        tabshow:true
    },

    onLoad: function(options) {
        var _self = this;
        this.setData({
            curTy: options.ty,
            from: options.from
        });
        this._getCateList();
        if (options.from == 'search') {
            search.init({
                page: _self,
                onSearch(q) {
                    _self.q = q;
                    _self._toTab(0, function() {
                        _self.setData({
                            dataLoaded: true
                        });
                    });
                }
            });
        } else {
            this._getZDList();
        }
        this._toTab(0, function() {
            _self.setData({
                dataLoaded: true
            });
        });

    },
    onShow: function() {
        this.setData({
            page: 1
        })
    },
    onPullDownRefresh() {
        var _self = this;
        var index = this._current || 0;
        this._toTab(index, function() {
            _self.setData({
                dataLoaded: true
            });
        });
    },
    onReachBottom: function() {
        this._loadMore();
    },
    /**
     * tab切换
     */
    _switchCat(evt) {

        var _self = this;
        var catId = evt.target.dataset.catId;

        this.setData({
            curTy: catId,
            page: 1,
            isCatHide: true,
        });

        this._getZDList();
        this._toTab(0, function() {
            _self.setData({
                dataLoaded: true
            });
        });
    },

    /**
     * 事件切换tab
     */
    _tabSwitch: function(evt) {
        var index = +evt.currentTarget.dataset.current || 0;
        this._current = index;
        var _self = this;
        var formId = evt.detail.formId;

        wx.getSetting({
            success: (res) => {
                if (index == 1) {
                     if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true)  {
                        util.alert('需要获取您的地理位置，请确认授权', function() {
                            wx.openSetting({
                                success: (res) => {
                                    _self._getUserLoc();
                                    /*
                                     * res.authSetting = {
                                     *   "scope.userInfo": true,
                                     *   "scope.userLocation": true
                                     * }
                                     */
                                }
                            })
                        })
                        return false;
                    }
                }

                this._toTab(index, function() {
                    _self.setData({
                        dataLoaded: true
                    });
                });
            }
        })

        common.submitForm(formId);
    },

    _toTab: function(index, cb) {
        this.setData({
            currentTab: index,
            page: 1,
            noMore: false,
        });
        this._getNoteList({ ty: index }, cb, true);
    },
    /**
     * 获取信息列表
     */
    _getNoteList: function(params, cb, isReset) {
        var self = this;
        var ty = params.ty;
        var isMore = params.isMore;
        var page = self.data.page || 1;
        var url = '';
        var lng = app.getLng();
        var lat = app.getLat();
        var cateId = this.data.curTy;
        var from = this.data.from;
        var currentTab = this.data.currentTab;
        var q = this.q;
        var from = this.data.from;
        var paramsData = {
            page: page,
            lng: lng || '',
            lat: lat || '',
        };


        if (from == 'search') { //搜索
            url = '/openapi/CInformation/search';
            paramsData.type = currentTab;
            paramsData.key = q || '';
        } else {
            switch (ty) {
                case 0:
                    url = '/openapi/CInformation/noteListOrderByTime';
                    break;
                case 1:
                    url = '/openapi/CInformation/noteListOrderByAddress';
                    break;
            }

            paramsData.cateId = cateId || '';
        }

        if (isMore) {
            self.setData({
                moreLoading: true
            });
        } else {
            self.setData({
                loading: true
            });
        }
        ajax.G(url, paramsData, function(data) {
            var list = data.result.noteList || [];
            var noteList = self.data.noteList;

            if (isReset) {
                noteList = [];
            }
            var toData = {
                noteList: noteList.concat(list),
                noMore: list.length == 0,
                page: self.data.page + 1,
            };
            if (toData.noteList.length == 0 && from == 'search') {
                toData['serchTip'] = '没有找到相关信息~';
            } else {
                toData['serchTip'] = '';
            }
            toData[isMore ? 'moreLoading' : 'loading'] = false;
            self.setData(toData);
            wx.stopPullDownRefresh() //停止下拉刷新
            cb && cb();
        });
    },

    /**
     * 加载更多
     */
    _loadMore: function() {
        if (this.data.moreLoading || this.data.loading || this.data.noMore) {
            return;
        }
        this._getNoteList({
            ty: this.data.currentTab,
            isMore: true
        });
    },
    /**
     * 页面跳转
     */
    _jump: function(evt) {
        common.jump(evt);
    },
    /**
     * 获取tab列表
     */
    _getCateList: function() {
        var url = "/openapi/CInformation/cateList";
        var _self = this;
        ajax.P(url, {}, function(data) {
            var data = data.result;
            _self.setData({
                catList: data.list
            })
        })
    },
    /**
     * 调用打电话功能
     */
    _calling: function(evt) {
        var phoneNumber = evt.currentTarget.dataset.phoneNumber;
        wx.makePhoneCall({
            phoneNumber: phoneNumber,
            success: function() {
            },
            fail: function() {
            }
        })
    },
    /**
    * 定位用户位置
    */ 
    _getUserLoc: function() {
        wx.getLocation({
            type: 'wgs84', //返回可以用于wx.openLocation的经纬度
            success: function(res) {
                var latitude = res.latitude;
                var longitude = res.longitude;
                app.setLng(longitude);
                app.setLat(latitude);
            }
        })
    },
    /**
    * 获取置顶信息
    */
    _getZDList: function(cb) {
        var _self = this;
        var from = this.data.from;
        var cateId = this.data.curTy;
        var url = '/openapi/CInformation/topStickNoteList';
        ajax.P(url, {
            cateId
        }, function(data) {
            _self.setData({
                zDList: data.result.list
            })
            cb && cb();
        })
    }
}))